const { body, param } = require("express-validator");
const validate = require("../middleware/validate");
const mongoose = require("mongoose");
const { Article } = require("../model");

// 创建文章
exports.createArticle = validate([
  body("article.title").notEmpty().withMessage("文章标题不能为空"),
  body("article.description").notEmpty().withMessage("文章摘要不能为空"),
  body("article.body").notEmpty().withMessage("文章内容不能为空"),
]);

// 获取文章
exports.getArticle = validate([
  param("articleId").custom(async (value) => {
    if (!mongoose.isValidObjectId(value)) {
      return Promise.reject("文章ID类型错误");

      // 同步：失败
      // throw new Error("文章ID类型错误");
    }
    // 同步：成功
    // return true
  }),
]);

exports.updateArticle = [
  validate([validate.isValidObjectId(["params"], "articleId")]),
  async (req, res, next) => {
    // 当前用户是否存在该文章
    const { articleId } = req.params;
    const article = await Article.findById(articleId);
    if (!article) {
      return res.status(404).json({
        code: 404,
        message: "文章不存在",
      });
    }
    req.article = article;
    next();
  },
  async (req, res, next) => {
    // 修改的文章作者是否是当前登录用户
    if (req.user._id.toString() !== req.article.author.toString()) {
      return res.status(403).json({
        code: 403,
        message: "你没有权限修改此文章",
      });
    }
    next();
  },
];

exports.deleteArticle = exports.updateArticle;
